'use strict';
const path = require('path');
const cp = require('child_process');
const Package = require('@gjs-cli-dev/package');
const log = require('@gjs-cli-dev/log');
const { exec: spawn } = require('@gjs-cli-dev/utils');


const SETTINGS = {
    init: '@gjs-cli-dev/init',
  };

  const CACHE_DIR = 'dependencies';

async function exec() {
    let targetPath = process.env.CLI_TARGET_PATH;
    const homePath = process.env.CLI_HOME_PATH;
    let storeDir = '';
    let pkg;
    // log.verbose('targetPath',targetPath);
    // log.verbose('homePath',homePath);
   
    const cmdObj = arguments[arguments.length - 1];
    const cmdName = cmdObj.name();
    const packageName = SETTINGS[cmdName];
    const packageVersion = 'latest';

    if (!targetPath) {
        targetPath = path.resolve(homePath, CACHE_DIR); // 生成缓存路径
        storeDir = path.resolve(targetPath, 'node_modules');
        log.verbose('targetPath', targetPath);
        log.verbose('storeDir', storeDir);
   
        // console.log(cmdObj)
        pkg = new Package({
            targetPath,
            // storeDir,
            packageName,
            packageVersion,
        });
        if (await pkg.exists()) {
            // 更新package
            await pkg.update();
            console.log('更新package')
        }else{
            // 安装package
          await pkg.install();
        }
   
    }  else {
        pkg = new Package({
            targetPath,
            // storeDir,
            packageName,
            packageVersion,
        });
    }
    console.log(pkg.exists());
    const rootFile = pkg.getRootFilePath();
    console.log(rootFile)
    if(rootFile){
        try {
            // 当前进程中调用 （希望改造成在子进程中调用，获得更多cup资源，后面的安装比较消耗性能）
            // require(rootFile).call(null, Array.from(arguments));
            const args = Array.from(arguments);
            const cmd = args[args.length - 1];

            const o = Object.create(null);
            Object.keys(cmd).forEach(key => {
                if (cmd.hasOwnProperty(key) &&
                !key.startsWith('_') &&
                key !== 'parent') {
                o[key] = cmd[key];
                }
            });
            // console.log('o', o)
            args[args.length - 1] = o;
            const code =  `require('${rootFile}').call(null, ${JSON.stringify(args)})`;
            const child = spawn('node', ['-e', code], {
                cwd: process.cwd(),
                stdio: 'inherit', //默认pipe管道，此模式下stdin stderr不用关注了
            });
            child.on('error', e => {
                log.error(e.message);
                process.exit(1);
              });
              child.on('exit', e => {
                log.verbose('命令执行成功:' + e);
                process.exit(e);
              });
           
        } catch (e) {
            log.error(e.message)
        }
       
    }
    // console.log(pkg.getRootFilePath());
    // console.log(pkg);
    // console.log('exec');
    // console.log(process.env.CLI_TARGET_PATH); // 缓存目录
    // console.log(process.env.CLI_HOME_PATH); // 缓存目录
}

// function spawn(command, args, options) {
//     const win32 = process.platform === 'win32';
  
//     const cmd = win32 ? 'cmd' : command;
//     const cmdArgs = win32 ? ['/c'].concat(command, args) : args;
  
//     return cp.spawn(cmd, cmdArgs, options || {});
// }

module.exports = exec;
